package com.waiting.component;

import com.waiting.config.SmsConfig;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.*;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

@Slf4j
@Component
public class SmsComponet {

  /** 发送地址 */
  private final String urlTemplate =
      "https://gyytz.market.alicloudapi.com/sms/smsSend?mobile=%s&templateId=%s&value=%s";

  @Autowired private RestTemplate restTemplate;

  @Autowired private SmsConfig smsConfig;

  public void sendSms(String mobile, String templateId, String value) {
    String url =
        String.format(
            urlTemplate, mobile, smsConfig.getTemplateId(), java.net.URLEncoder.encode(value));
    HttpHeaders headers = new HttpHeaders();
    // 最后在header中的格式(中间是英文空格)为Authorization:APPCODE 83359fd73fe94948385f570e3c139105
    headers.set("Authorization", "APPCODE " + smsConfig.getAppCode());
    HttpEntity<String> entity = new HttpEntity<>(headers);
    ResponseEntity<String> response =
        restTemplate.exchange(url, HttpMethod.POST, entity, String.class);
    log.info("发送短信结果:{}", response.getBody());
    if (response.getStatusCode() == HttpStatus.OK) {
      log.info("发送短信成功");
    } else {
      log.error("发送短信失败{}", response.getBody());
    }
  }
}
